package com.astersoft.lib.net.impl;

/*
 * Copyright 2012 AsterSoft personal developer - Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ASNet5 {
	public static byte[] getMac() 
	throws Exception {
		Process aProc = Runtime.getRuntime().exec("ipconfig /all");
		InputStream procOut = new DataInputStream(aProc.getInputStream());
		BufferedReader br = new BufferedReader(new InputStreamReader(procOut));
	
		String aMacAddress = "((\\p{XDigit}\\p{XDigit}-){5}\\p{XDigit}\\p{XDigit})";
		Pattern aPatternMac = Pattern.compile(aMacAddress);
		String aIpAddress = ".*IP.*: (([0-9]*\\.){3}[0-9]).*$";
		Pattern aPatternIp = Pattern.compile(aIpAddress);
		String aNewAdaptor = "[A-Z].*$";
		Pattern aPatternNewAdaptor = Pattern.compile(aNewAdaptor);
	
		// locate first MAC address that has IP address
		boolean zFoundMac = false;
		boolean zFoundIp = false;
		String foundMac = null;
		String theGoodMac = null;
	
		String strLine;
		while (((strLine = br.readLine()) != null) && !(zFoundIp && zFoundMac)) {
			Matcher aMatcherNewAdaptor = aPatternNewAdaptor.matcher(strLine);
			if (aMatcherNewAdaptor.matches()) {
				zFoundMac = zFoundIp = false;
			}
			Matcher aMatcherMac = aPatternMac.matcher(strLine);
			if (aMatcherMac.find()) {
				foundMac = aMatcherMac.group(0);
				zFoundMac = true;
			}
			Matcher aMatcherIp = aPatternIp.matcher(strLine);
			if (aMatcherIp.matches()) {
				zFoundIp = true;
				if(zFoundMac && (theGoodMac == null)) theGoodMac = foundMac;
			}
		}
	
		aProc.destroy();
		aProc.waitFor();

		return theGoodMac.getBytes();
	}
}
